<template>
    <div id="add-edit-model">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <div>
                <el-divider content-position="left">基础信息</el-divider>  
                <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="120px" :rules="rules">
                    <el-row>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="课程类型" prop="v_CourseType">
                                <el-select 
                                    filterable
                                    class="m-2" 
                                    placeholder="请选择课程类型" 
                                    v-model="ruleForm.v_CourseType" 
                                    @change="courseChange"
                                >
                                    <el-option
                                        v-for="item in courseOption"
                                        :key="item.id"
                                        :label="item.value"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="计划培训时间">
                                <el-date-picker
                                    v-model="ruleForm.v_PlanMonth"
                                    type="date"
                                    value-format="YYYY-MM-DD"
                                    placeholder="请选择计划培训时间">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="课程名称" prop="v_CourseName">
                                <el-input v-model="ruleForm.v_CourseName" placeholder="请输入课程名称" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="培训讲师">
                                <el-input v-model="ruleForm.v_Teacher" placeholder="请输入培训讲师" clearable />
                            </el-form-item>
                        </el-col>
                        <!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="培训对象" prop="v_Trainee">
                                <el-input v-model="ruleForm.v_Trainee" placeholder="请输入培训对象" clearable />
                            </el-form-item>
                        </el-col> -->
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="用户">
                                <!-- <el-input v-model="ruleForm.userIds" placeholder="请在用户中选择培训对象" clearable /> -->
                                <el-select 
                                    filterable
                                    multiple
                                    collapse-tags
                                    class="m-2" 
                                    placeholder="请在用户中选择培训对象" 
                                    v-model="ruleForm.userIds"
                                >
                                    <el-option
                                        v-for="item in userOption"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="部门">
                                <!-- <el-cascader
                                    v-model="ruleForm.orgIds"
                                    :options="orgOption"
                                    :props="orgProps"
                                    @change="orgChange"
                                    :max-collapse-tags="2"
                                    filterable
                                    clearable 
                                    collapse-tags
                                /> -->
                                <el-cascader
                                    v-model="selectedValues"
                                    :options="orgOption"
                                    :props="orgProps"
                                    @change="orgChange"
                                    :max-collapse-tags="2"
                                    filterable
                                    clearable 
                                    collapse-tags
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="岗位"> 
                                <!-- <el-input v-model="ruleForm.posIds" placeholder="请在岗位中选择培训对象" clearable /> -->
                                <el-select 
                                    filterable
                                    multiple
                                    collapse-tags
                                    class="m-2" 
                                    placeholder="请在岗位中选择培训对象" 
                                    v-model="ruleForm.posIds"
                                >
                                    <el-option
                                        v-for="item in posOption"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="培训时长(分钟)">
                                <el-input v-model="ruleForm.n_Mins" type="number" placeholder="请输入培训时长" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="是否需要考试">
                                <el-switch
                                    v-model="ruleForm.isNeedExam"
                                    active-color="#07AAF9"
                                    inactive-color="#FF5F33"
                                    inline-prompt
                                    active-text="需要"
                                    inactive-text="不需要"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                            <el-form-item label="培训内容" prop="v_Content">
                                <el-input type="textarea" v-model="ruleForm.v_Content" placeholder="请输入培训内容" clearable />
                            </el-form-item>
                        </el-col>
                        <!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="启用状态">
                                <el-switch
                                    v-model="ruleForm.n_States"
                                    active-color="#07AAF9"
                                    inactive-color="#FF5F33"
                                    inline-prompt
                                    active-text="需要"
                                    inactive-text="不需要"
                                />
                            </el-form-item>
                        </el-col> -->
                    </el-row>
                </el-form>
            </div>
            
            <template #footer>
                <el-button @click="cancelUseClick">取 消</el-button>
                <el-button type="primary" :loading="repeatDis" :disabled="repeatDis" @click="submitForm(ruleFormRef)">提 交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch } from 'vue';
import { FormInstance, FormRules , ElMessage, ElButton, ElCol, ElDatePicker, ElDialog, ElDivider, ElForm, ElFormItem, ElInput, ElOption, ElRadio, ElRow, ElSelect, ElTable, ElTableColumn } from 'element-plus';
import { EduTrainingPlanAdd , sysDictDataList , EduTrainingPlanUpdate } from '/@/api/centerControl/sms';
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    v_CourseType: String,
    v_PlanMonth: String,
    v_CourseName: String,
    v_Teacher: String,
    v_Content: String,
    v_Trainee: String,
    n_Mins: Number,
    isNeedExam: Boolean,
    userIds: any,
    orgIds: any,
    posIds: any,
    // n_States: Boolean,
}
export default defineComponent( {
    name: 'add-edit-model',
    components: {},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        },
        personInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const titleCon = ref();
        const ruleFormRef = ref();
        const courseOption = ref();
        const posOption = ref();
        const userOption = ref();
        const orgOption: any = ref();
        const selectedIds:any = ref([]);

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            // 课程类型
            v_CourseType: [
				{ required: true, message: '请输入课程类型', trigger: 'blur' },
			],
            // 课程类型
            v_CourseName: [
				{ required: true, message: '请输入课程名称', trigger: 'blur' },
			],
            // 培训内容
            v_Content: [
				{ required: true, message: '请输入培训内容', trigger: 'blur' },
			],
            // 培训对象
            v_Trainee: [
				{ required: true, message: '请输入培训对象', trigger: 'blur' },
			],
        });

        /*** courseChange 课程类型选择事件 */
        const courseChange = (val:any) => {
            console.log(val,'val')
        };
        const selectedValues: any = [];
        /*** 部门下拉框改变事件 */
        const orgChange = (value: any) => {
            selectedValues.value = value;
            selectedIds.value = [];
            value.forEach((val: any) => {
                const node = findNode(orgOption.value, val);
                if (node) {
                    selectedIds.value.push(node.id);
                    if (node.children) {
                        collectChildIds(node);
                    }
                }
            });
            if(selectedIds.value.length !== 0){
                selectedIds.value = [...new Set(selectedIds.value)];
            }
            state.ruleForm.orgIds = selectedValues.value;
        };

        const findNode = (nodes: any, value: any) => {
            for (let node of nodes) {
                if (node.id === value) return node;
                if (node.children) {
                    const result: any = findNode(node.children, value);
                    if (result) return result;
                }
            }
            return null;
        };

        const collectChildIds = (node: any) => {
            node.children.forEach((child: any) => {
                selectedIds.value.push(child.id);
                if (child.children) {
                    collectChildIds(child);
                }
            });
        };

        /*** getDictFun 获取课程类型字典值 */
        const getDictFun = async() => {
            let res: any = await sysDictDataList( {TypeCode: 'CourseType'} );
            if(res.success) courseOption.value = res.data;
        };

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            ctx.emit('cancelUseClick')
        };

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelUseClick')
        };

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    if(
                        state.ruleForm.orgIds.length === 0 && 
                        state.ruleForm.userIds.length === 0 && 
                        state.ruleForm.posIds.length === 0
                    ){
                        ElMessage({
                            type: 'warning',
                            message: '请选择需要培训的对象',
                        });
                        return;
                    }
                    state.repeatDis = true;
                    let param = toRaw(state.ruleForm);
                    if(props.repairInfo !== ''){
                        try{
                            let res:any = await EduTrainingPlanUpdate(param);
                            if(res.success){
                                state.repeatDis = false;
                                ctx.emit('updateData');
                                ctx.emit('controlUseClick');
                            }else{
                                state.repeatDis = false;
                                ctx.emit('controlUseClick');
                            }
                        } catch (err) { 
                            state.repeatDis = false;
                            ctx.emit('controlUseClick');
                        }
                    }else{
                        try{
                            let res:any = await EduTrainingPlanAdd(param);
                            if(res.success){
                                state.repeatDis = false;
                                ctx.emit('updateData');
                                ctx.emit('controlUseClick');
                            }else{
                                state.repeatDis = false;
                                ctx.emit('controlUseClick');
                            }
                        } catch (err) { 
                            state.repeatDis = false;
                            ctx.emit('controlUseClick');
                        }
                    }
                }else{
                    console.log('error submit!')
					return false
                }
            })
        };

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        };

        /*** clearFileFun 清空文件 */
        const clearFileFun = () => {};

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                getDictFun(); // 获取课程类型数据
                console.log(JSON.parse(props.personInfo),'personInfo12')
                posOption.value = JSON.parse(props.personInfo).posInfo;
                userOption.value = JSON.parse(props.personInfo).userInfo;
                orgOption.value = JSON.parse(props.personInfo).treeInfo;
                selectedValues.value = [];
                state.ruleForm.orgIds = [];
                if(props.repairInfo !== ''){
                    titleCon.value = '编辑'
                    // 状态数据重置
                    state.repeatDis = false;
                    let getData = JSON.parse(props.repairInfo);
                    state.ruleForm = getData;
                }else{
                    titleCon.value = '新增';
                    state.ruleForm = {
                        v_CourseType: '',
                        v_PlanMonth: '',
                        v_CourseName: '',
                        v_Teacher: '',
                        v_Content: '',
                        v_Trainee: '',
                        n_Mins: 0,
                        isNeedExam: true,
                        userIds: [],
                        orgIds: [],
                        posIds: [],
                        // n_States: true,
                    }
                }
            }
        });

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        });

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            courseOption,
            courseChange,
            posOption,
            userOption,
            orgOption,
            orgProps: { multiple: true, checkStrictly: true, emitPath: false, label: 'title', value: 'id', children: 'children' },
            // orgProps: { multiple: true, emitPath: false, label: 'title', value: 'id', children: 'children' },
            orgChange,
            selectedValues,
        }
    },
} )
</script>
<style scoped lang="scss">
:deep(.el-select){
    width: 100%!important;
}
:deep(.el-input){
    width: 100%;
}
:deep(.el-cascader){
    width: 100%;
}
</style>